import 'package:device_info/device_info.dart';
import 'package:package_info/package_info.dart';
import 'common/model/model.dart';
import 'common/utils/utils.dart';
import 'common/values/values.dart';


/// 全局配置
class Global {
  /// 用户配置
  static User loginUserInfo = User();

  static String? token;

  /// 发布渠道
  static String channel = "xiaomi";

  /// android 设备信息
  static late AndroidDeviceInfo androidDeviceInfo;

  /// ios 设备信息
  static late IosDeviceInfo iosDeviceInfo;

  /// 包信息
  static late PackageInfo packageInfo;

  /// 是否第一次打开
  static bool? isFirstOpen;

  /// 是否离线登录
  static bool isOfflineLogin = false;

  /// 是否 release
  static bool get isRelease => bool.fromEnvironment("dart.vm.product");


  static Future<void> init() async {

    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();

    if(PlatformUtil.isIOS){
      iosDeviceInfo = await deviceInfoPlugin.iosInfo;
    }

    if(PlatformUtil.isAndroid){
      androidDeviceInfo = await deviceInfoPlugin.androidInfo;
    }

    // 读取设备第一次打开
    isFirstOpen = StorageUtil().getBool(STORAGE_DEVICE_FIRST_OPEN_KEY);
    print("Global.isFirstOpen-->${Global.isFirstOpen}");
    if (isFirstOpen == null) {
      isFirstOpen = true;
    }

    // 读取离线token
    var _token = StorageUtil().getStr(STORAGE_TOKEN_KEY);
    print("获取离线的token-->$_token");
    if (_token != null) {
      token = _token;
      isOfflineLogin = true;
    }

    // 读取离线用户信息
    dynamic _profileJSON = StorageUtil().getJSON(STORAGE_USER_PROFILE_KEY);
    print("获取离线的用户信息-->$_profileJSON");
    if (_profileJSON != null) {
      loginUserInfo = User.fromJson(_profileJSON);
      // isOfflineLogin = true;
    }
  }


  // 保存用户已打开APP
  static saveAlreadyOpen() {
    StorageUtil().setBool(STORAGE_DEVICE_FIRST_OPEN_KEY, false);
  }

  // 持久化 Token信息
  static Future<bool>? saveToken(String accessToken) {
    token = accessToken;
    return StorageUtil().setStr(STORAGE_TOKEN_KEY, accessToken);
  }


  // 持久化 用户信息
  static Future<bool>? saveLoginUserInfo(User userInfo) {
    loginUserInfo = userInfo;
    return StorageUtil().setJSON(STORAGE_USER_PROFILE_KEY, userInfo.toJson());
  }
}